package cn.gpdi.framework.util;

import cn.gpdi.framework.dao.CommDAO;
import cn.gpdi.framework.iface.IDAO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by 司徒鑫(QQ:156845600) on 2017/5/24.
 */
public class CommUtil implements ApplicationContextAware {

    private static Logger logger = Logger.getLogger(CommUtil.class);

    private static ApplicationContext applicationContext;

    private static Map<String, Object> map = new HashMap<String, Object>();

    public static void setSysListTableCfg(String key, Object val) {
        map.put(key, val);
    }

    public static Object getSysListTableCfg(String key) {
        return map.get(key);
    }

    //读取配置文件
    private static Properties properties = null;
    // 使用ClassLoader加载properties配置文件生成对应的输入流

    public static void  getFile(String fileName) throws IOException{
        logger.debug("读取配置文件:"+"["+fileName+"]");
        if(properties!=null){
            return;
        }
        properties = new Properties();
         InputStream in = CommUtil.class.getClassLoader().getResourceAsStream(fileName);
        try {
            properties.load(in);
        } catch (IOException ex) {
            logger.error("["+fileName+"]文件加载异常。");
            ex.printStackTrace();
            throw new IOException("["+fileName+"]文件加载异常。");
        }

    }
    public static String getPropVal(String key) throws IOException{
        return properties.getProperty(key);
    }

    /**
     * 解密BASE64字窜
     *
     * @param s
     * @return
     */
    public static String decodeBASE64(String s) throws IOException {
        byte[] b = null;
        BASE64Decoder decoder = new BASE64Decoder();
        b = decoder.decodeBuffer(s);
        return new String(b, "utf-8");
    }

    /**
     * 用BASE64加密
     *
     * @param str
     * @return
     */
    private static String getBASE64(String str) throws UnsupportedEncodingException {
        byte[] b = str.getBytes("utf-8");
        String s = null;
        if (b != null) {
            s = new sun.misc.BASE64Encoder().encode(b);
        }
        return s;
    }

    public static String getDBTime() throws Exception {
        CommDAO commDAO = (CommDAO) getBean("commDAO");
        String time = commDAO.querySQL("select date_format(now(),'%Y%m%d%H%i%s') time").get(0).get("time").toString();
        //下面为ORACLE专用
        //Map m=new HashMap<String,Object>();
        // m.put("FORMAT","YYYY-MM-DD HH24:MI:SS");
        // ((String)((IDAO) getBean("commDAO",CommDAO.class)).selectOneType("FW_CONFIG.sysdate", m))
        return time;
    }

    public static String getDBTime(String format) throws Exception {

        Map m = new HashMap<String, Object>();
        m.put("FORMAT", format);
        return ((String) ((IDAO) getBean("commDAO")).selectOneType(
                "FW_CONFIG.sysdate", m));
    }


    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public static String getOracleSeq(String seq) throws Exception {
        return ((IDAO) getBean("commDAO")).querySQL("SELECT " + seq + ".NEXTVAL SEQ FROM dual").get(0).get("SEQ").toString();
    }

    public static Map getSucessMap(Object dataMap) {
        Map m = new HashMap();
        m.put("result", "1");
        m.put("data", dataMap);
        return m;
    }

    public static Map getFailMap(Object dataMap) {
        Map m = new HashMap();
        m.put("result", "-1");
        m.put("data", dataMap);
        return m;
    }

    /**
     * Map转JSON字符串
     *
     * @param m
     * @return
     * @throws com.fasterxml.jackson.core.JsonProcessingException
     */
    public static String Obj2JSONStr(Object m) throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(m);
    }

    /**
     * JSON字符串转MAP对象
     *
     * @return
     * @throws com.fasterxml.jackson.core.JsonProcessingException
     */
    public static Map JSONStr2Map(String str) throws IOException {
        return new ObjectMapper().readValue(str, Map.class);
    }
    public static List JSONStr2List(String str) throws IOException {
        return new ObjectMapper().readValue(str, List.class);
    }

    public static boolean isEmpty(Object str) {
        return ((str == null) || ("".equals(((String)str).trim())));
    }

    //通过json的请求，转换为map
    //注意 request 只能获取一次 getInputStream
    public static Map Req2Map(HttpServletRequest request) {
        BufferedReader br;
        StringBuilder sb = null;
        String reqBody = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
            reqBody = reqBody.substring(reqBody.indexOf("{"));
            request.setAttribute("inputParam", reqBody);
            return JSONStr2Map(reqBody);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return  null;
        }
    }

}
